3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "logoutputbuffer.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
64 #include "sound_openal.h"
67 #ifdef HAVE_TOUCHSCREENGUI
68 #include "touchscreengui.h"
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
78 struct TextDestNodeMetadata : public TextDest {
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(std::wstring text)
87 std::string ntext = wide_to_narrow(text);
88 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
90 std::map<std::string, std::string> fields;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(std::map<std::string, std::string> fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest {
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, std::string formname)
112 m_formname = formname;
114 void gotText(std::map<std::string, std::string> fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest {
123 LocalFormspecHandler();
124 LocalFormspecHandler(std::string formname) :
127 m_formname = formname;
130 LocalFormspecHandler(std::string formname, Client *client) :
133 m_formname = formname;
136 void gotText(std::wstring message)
138 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
141 void gotText(std::map<std::string, std::string> fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
178 if (m_formname == "MT_CHAT_MENU") {
179 assert(m_client != 0);
181 if ((fields.find("btn_send") != fields.end()) ||
182 (fields.find("quit") != fields.end())) {
183 if (fields.find("f_text") != fields.end()) {
184 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
191 if (m_formname == "MT_DEATH_SCREEN") {
192 assert(m_client != 0);
194 if ((fields.find("btn_respawn") != fields.end())) {
195 m_client->sendRespawn();
199 if (fields.find("quit") != fields.end()) {
200 m_client->sendRespawn();
205 // don't show error message for unhandled cursor keys
206 if ((fields.find("key_up") != fields.end()) ||
207 (fields.find("key_down") != fields.end()) ||
208 (fields.find("key_left") != fields.end()) ||
209 (fields.find("key_right") != fields.end())) {
213 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
216 for (std::map<std::string, std::string>::iterator iter = fields.begin();
217 iter != fields.end(); iter++) {
218 errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
226 /* Form update callback */
228 class NodeMetadataFormSource: public IFormSource
231 NodeMetadataFormSource(ClientMap *map, v3s16 p):
236 std::string getForm()
238 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
243 return meta->getString("formspec");
245 std::string resolveText(std::string str)
247 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
252 return meta->resolveString(str);
259 class PlayerInventoryFormSource: public IFormSource
262 PlayerInventoryFormSource(Client *client):
266 std::string getForm()
268 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
269 return player->inventory_formspec;
276 Check if a node is pointable
278 inline bool isPointableNode(const MapNode &n,
279 Client *client, bool liquids_pointable)
281 const ContentFeatures &features = client->getNodeDefManager()->get(n);
282 return features.pointable ||
283 (liquids_pointable && features.isLiquid());
287 Find what the player is pointing at
289 PointedThing getPointedThing(Client *client, v3f player_position,
290 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
291 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
292 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
296 hilightboxes.clear();
297 selected_object = NULL;
299 INodeDefManager *nodedef = client->getNodeDefManager();
300 ClientMap &map = client->getEnv().getClientMap();
302 f32 mindistance = BS * 1001;
304 // First try to find a pointed at active object
305 if (look_for_object) {
306 selected_object = client->getSelectedActiveObject(d * BS,
307 camera_position, shootline);
309 if (selected_object != NULL) {
310 if (selected_object->doShowSelectionBox()) {
311 aabb3f *selection_box = selected_object->getSelectionBox();
312 // Box should exist because object was
313 // returned in the first place
314 assert(selection_box);
316 v3f pos = selected_object->getPosition();
317 hilightboxes.push_back(aabb3f(
318 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
319 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
322 mindistance = (selected_object->getPosition() - camera_position).getLength();
324 result.type = POINTEDTHING_OBJECT;
325 result.object_id = selected_object->getId();
329 // That didn't work, try to find a pointed at node
332 v3s16 pos_i = floatToInt(player_position, BS);
334 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
338 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
339 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
340 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
341 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
342 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
343 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
345 // Prevent signed number overflow
355 for (s16 y = ystart; y <= yend; y++)
356 for (s16 z = zstart; z <= zend; z++)
357 for (s16 x = xstart; x <= xend; x++) {
359 bool is_valid_position;
361 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
362 if (!is_valid_position)
365 if (!isPointableNode(n, client, liquids_pointable))
368 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
371 v3f npf = intToFloat(np, BS);
373 for (std::vector<aabb3f>::const_iterator
375 i != boxes.end(); i++) {
380 for (u16 j = 0; j < 6; j++) {
381 v3s16 facedir = g_6dirs[j];
382 aabb3f facebox = box;
387 facebox.MinEdge.X = facebox.MaxEdge.X - d;
388 else if (facedir.X < 0)
389 facebox.MaxEdge.X = facebox.MinEdge.X + d;
390 else if (facedir.Y > 0)
391 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
392 else if (facedir.Y < 0)
393 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
394 else if (facedir.Z > 0)
395 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
396 else if (facedir.Z < 0)
397 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
399 v3f centerpoint = facebox.getCenter();
400 f32 distance = (centerpoint - camera_position).getLength();
402 if (distance >= mindistance)
405 if (!facebox.intersectsWithLine(shootline))
408 v3s16 np_above = np + facedir;
410 result.type = POINTEDTHING_NODE;
411 result.node_undersurface = np;
412 result.node_abovesurface = np_above;
413 mindistance = distance;
415 hilightboxes.clear();
417 if (!g_settings->getBool("enable_node_highlighting")) {
418 for (std::vector<aabb3f>::const_iterator
420 i2 != boxes.end(); i2++) {
422 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
423 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
424 hilightboxes.push_back(box);
434 /* Profiler display */
436 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
437 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
439 if (show_profiler == 0) {
440 guitext_profiler->setVisible(false);
443 std::ostringstream os(std::ios_base::binary);
444 g_profiler->printPage(os, show_profiler, show_profiler_max);
445 std::wstring text = narrow_to_wide(os.str());
446 guitext_profiler->setText(text.c_str());
447 guitext_profiler->setVisible(true);
449 s32 w = fe->getTextWidth(text.c_str());
454 unsigned text_height = fe->getTextHeight();
456 core::position2di upper_left, lower_right;
459 upper_left.Y = (text_height + 5) * 2;
460 lower_right.X = 12 + w;
461 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
463 if (lower_right.Y > screen_height * 2 / 3)
464 lower_right.Y = screen_height * 2 / 3;
466 core::rect<s32> rect(upper_left, lower_right);
468 guitext_profiler->setRelativePosition(rect);
469 guitext_profiler->setVisible(true);
477 Profiler::GraphValues values;
483 Meta(float initial = 0,
484 video::SColor color = video::SColor(255, 255, 255, 255)):
490 std::vector<Piece> m_log;
498 void put(const Profiler::GraphValues &values)
501 piece.values = values;
502 m_log.push_back(piece);
504 while (m_log.size() > m_log_max_size)
505 m_log.erase(m_log.begin());
508 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
509 gui::IGUIFont *font) const
511 std::map<std::string, Meta> m_meta;
513 for (std::vector<Piece>::const_iterator k = m_log.begin();
514 k != m_log.end(); k++) {
515 const Piece &piece = *k;
517 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
518 i != piece.values.end(); i++) {
519 const std::string &id = i->first;
520 const float &value = i->second;
521 std::map<std::string, Meta>::iterator j =
524 if (j == m_meta.end()) {
525 m_meta[id] = Meta(value);
529 if (value < j->second.min)
530 j->second.min = value;
532 if (value > j->second.max)
533 j->second.max = value;
538 static const video::SColor usable_colors[] = {
539 video::SColor(255, 255, 100, 100),
540 video::SColor(255, 90, 225, 90),
541 video::SColor(255, 100, 100, 255),
542 video::SColor(255, 255, 150, 50),
543 video::SColor(255, 220, 220, 100)
545 static const u32 usable_colors_count =
546 sizeof(usable_colors) / sizeof(*usable_colors);
547 u32 next_color_i = 0;
549 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
550 i != m_meta.end(); i++) {
551 Meta &meta = i->second;
552 video::SColor color(255, 200, 200, 200);
554 if (next_color_i < usable_colors_count)
555 color = usable_colors[next_color_i++];
561 s32 textx = x_left + m_log_max_size + 15;
562 s32 textx2 = textx + 200 - 15;
565 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
566 i != m_meta.end(); i++) {
567 const std::string &id = i->first;
568 const Meta &meta = i->second;
570 s32 y = y_bottom - meta_i * 50;
571 float show_min = meta.min;
572 float show_max = meta.max;
574 if (show_min >= -0.0001 && show_max >= -0.0001) {
575 if (show_min <= show_max * 0.5)
581 snprintf(buf, 10, "%.3g", show_max);
582 font->draw(narrow_to_wide(buf).c_str(),
583 core::rect<s32>(textx, y - graphh,
584 textx2, y - graphh + texth),
586 snprintf(buf, 10, "%.3g", show_min);
587 font->draw(narrow_to_wide(buf).c_str(),
588 core::rect<s32>(textx, y - texth,
591 font->draw(narrow_to_wide(id).c_str(),
592 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
593 textx2, y - graphh / 2 + texth / 2),
596 s32 graph1h = graphh;
597 bool relativegraph = (show_min != 0 && show_min != show_max);
598 float lastscaledvalue = 0.0;
599 bool lastscaledvalue_exists = false;
601 for (std::vector<Piece>::const_iterator j = m_log.begin();
602 j != m_log.end(); j++) {
603 const Piece &piece = *j;
605 bool value_exists = false;
606 Profiler::GraphValues::const_iterator k =
607 piece.values.find(id);
609 if (k != piece.values.end()) {
616 lastscaledvalue_exists = false;
620 float scaledvalue = 1.0;
622 if (show_max != show_min)
623 scaledvalue = (value - show_min) / (show_max - show_min);
625 if (scaledvalue == 1.0 && value == 0) {
627 lastscaledvalue_exists = false;
632 if (lastscaledvalue_exists) {
633 s32 ivalue1 = lastscaledvalue * graph1h;
634 s32 ivalue2 = scaledvalue * graph1h;
635 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
636 v2s32(x, graph1y - ivalue2), meta.color);
639 lastscaledvalue = scaledvalue;
640 lastscaledvalue_exists = true;
642 s32 ivalue = scaledvalue * graph1h;
643 driver->draw2DLine(v2s32(x, graph1y),
644 v2s32(x, graph1y - ivalue), meta.color);
655 class NodeDugEvent: public MtEvent
661 NodeDugEvent(v3s16 p, MapNode n):
665 const char *getType() const
673 ISoundManager *m_sound;
674 INodeDefManager *m_ndef;
676 float m_player_step_timer;
678 SimpleSoundSpec m_player_step_sound;
679 SimpleSoundSpec m_player_leftpunch_sound;
680 SimpleSoundSpec m_player_rightpunch_sound;
682 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
685 m_player_step_timer(0)
689 void playPlayerStep()
691 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
692 m_player_step_timer = 0.03;
693 m_sound->playSound(m_player_step_sound, false);
697 static void viewBobbingStep(MtEvent *e, void *data)
699 SoundMaker *sm = (SoundMaker *)data;
700 sm->playPlayerStep();
703 static void playerRegainGround(MtEvent *e, void *data)
705 SoundMaker *sm = (SoundMaker *)data;
706 sm->playPlayerStep();
709 static void playerJump(MtEvent *e, void *data)
711 //SoundMaker *sm = (SoundMaker*)data;
714 static void cameraPunchLeft(MtEvent *e, void *data)
716 SoundMaker *sm = (SoundMaker *)data;
717 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
720 static void cameraPunchRight(MtEvent *e, void *data)
722 SoundMaker *sm = (SoundMaker *)data;
723 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
726 static void nodeDug(MtEvent *e, void *data)
728 SoundMaker *sm = (SoundMaker *)data;
729 NodeDugEvent *nde = (NodeDugEvent *)e;
730 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
733 static void playerDamage(MtEvent *e, void *data)
735 SoundMaker *sm = (SoundMaker *)data;
736 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
739 static void playerFallingDamage(MtEvent *e, void *data)
741 SoundMaker *sm = (SoundMaker *)data;
742 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
745 void registerReceiver(MtEventManager *mgr)
747 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
748 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
749 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
750 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
751 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
752 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
753 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
754 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
757 void step(float dtime)
759 m_player_step_timer -= dtime;
763 // Locally stored sounds don't need to be preloaded because of this
764 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
766 std::set<std::string> m_fetched;
768 void fetchSounds(const std::string &name,
769 std::set<std::string> &dst_paths,
770 std::set<std::string> &dst_datas)
772 if (m_fetched.count(name))
775 m_fetched.insert(name);
776 std::string base = porting::path_share + DIR_DELIM + "testsounds";
777 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
778 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
779 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
780 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
791 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
794 bool *m_force_fog_off;
800 void onSettingsChange(const std::string &name)
802 if (name == "enable_fog")
803 m_fogEnabled = g_settings->getBool("enable_fog");
806 static void SettingsCallback(const std::string name, void *userdata)
808 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
811 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
812 f32 *fog_range, Client *client) :
814 m_force_fog_off(force_fog_off),
815 m_fog_range(fog_range),
818 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
819 m_fogEnabled = g_settings->getBool("enable_fog");
822 ~GameGlobalShaderConstantSetter()
824 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
827 virtual void onSetConstants(video::IMaterialRendererServices *services,
834 video::SColor bgcolor = m_sky->getBgColor();
835 video::SColorf bgcolorf(bgcolor);
836 float bgcolorfa[4] = {
842 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
845 float fog_distance = 10000 * BS;
847 if (m_fogEnabled && !*m_force_fog_off)
848 fog_distance = *m_fog_range;
850 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
853 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
854 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
855 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
857 u32 animation_timer = porting::getTimeMs() % 100000;
858 float animation_timer_f = (float)animation_timer / 100000.0;
859 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
860 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
862 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
863 v3f eye_position = player->getEyePosition();
864 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
865 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
867 // Uniform sampler layers
871 // before 1.8 there isn't a "integer interface", only float
872 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
873 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
874 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
875 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
877 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
878 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
879 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
884 bool nodePlacementPrediction(Client &client,
885 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
887 std::string prediction = playeritem_def.node_placement_prediction;
888 INodeDefManager *nodedef = client.ndef();
889 ClientMap &map = client.getEnv().getClientMap();
891 bool is_valid_position;
893 node = map.getNodeNoEx(nodepos, &is_valid_position);
894 if (!is_valid_position)
897 if (prediction != "" && !nodedef->get(node).rightclickable) {
898 verbosestream << "Node placement prediction for "
899 << playeritem_def.name << " is "
900 << prediction << std::endl;
901 v3s16 p = neighbourpos;
903 // Place inside node itself if buildable_to
904 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
905 if (is_valid_position)
907 if (nodedef->get(n_under).buildable_to)
910 node = map.getNodeNoEx(p, &is_valid_position);
911 if (is_valid_position &&!nodedef->get(node).buildable_to)
916 // Find id of predicted node
918 bool found = nodedef->getId(prediction, id);
921 errorstream << "Node placement prediction failed for "
922 << playeritem_def.name << " (places "
924 << ") - Name not known" << std::endl;
928 // Predict param2 for facedir and wallmounted nodes
931 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
932 v3s16 dir = nodepos - neighbourpos;
934 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
935 param2 = dir.Y < 0 ? 1 : 0;
936 } else if (abs(dir.X) > abs(dir.Z)) {
937 param2 = dir.X < 0 ? 3 : 2;
939 param2 = dir.Z < 0 ? 5 : 4;
943 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
944 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
946 if (abs(dir.X) > abs(dir.Z)) {
947 param2 = dir.X < 0 ? 3 : 1;
949 param2 = dir.Z < 0 ? 2 : 0;
955 //Check attachment if node is in group attached_node
956 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
957 static v3s16 wallmounted_dirs[8] = {
967 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
968 pp = p + wallmounted_dirs[param2];
970 pp = p + v3s16(0, -1, 0);
972 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
976 // Add node to client map
977 MapNode n(id, 0, param2);
980 LocalPlayer *player = client.getEnv().getLocalPlayer();
982 // Dont place node when player would be inside new node
983 // NOTE: This is to be eventually implemented by a mod as client-side Lua
984 if (!nodedef->get(n).walkable ||
985 g_settings->getBool("enable_build_where_you_stand") ||
986 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
987 (nodedef->get(n).walkable &&
988 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
989 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
991 // This triggers the required mesh update too
992 client.addNode(p, n);
995 } catch (InvalidPositionException &e) {
996 errorstream << "Node placement prediction failed for "
997 << playeritem_def.name << " (places "
999 << ") - Position not loaded" << std::endl;
1006 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1007 InventoryManager *invmgr, IGameDef *gamedef,
1008 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1009 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1012 if (*cur_formspec == 0) {
1013 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1014 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1015 (*cur_formspec)->doPause = false;
1018 Caution: do not call (*cur_formspec)->drop() here --
1019 the reference might outlive the menu, so we will
1020 periodically check if *cur_formspec is the only
1021 remaining reference (i.e. the menu was removed)
1022 and delete it in that case.
1026 (*cur_formspec)->setFormSource(fs_src);
1027 (*cur_formspec)->setTextDest(txt_dest);
1032 #define SIZE_TAG "size[11,5.5]"
1034 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1037 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1038 InventoryManager *invmgr, IGameDef *gamedef,
1039 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1040 Client *client, std::string text)
1042 std::string formspec =
1043 FORMSPEC_VERSION_STRING
1045 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1046 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1050 /* Note: FormspecFormSource and LocalFormspecHandler
1051 * are deleted by guiFormSpecMenu */
1052 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1053 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1055 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1058 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1059 InventoryManager *invmgr, IGameDef *gamedef,
1060 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1062 std::string formspec =
1063 std::string(FORMSPEC_VERSION_STRING) +
1065 "bgcolor[#320000b4;true]"
1066 "label[4.85,1.35;" + gettext("You died.") + "]"
1067 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1071 /* Note: FormspecFormSource and LocalFormspecHandler
1072 * are deleted by guiFormSpecMenu */
1073 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1074 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1076 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1079 /******************************************************************************/
1080 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1081 InventoryManager *invmgr, IGameDef *gamedef,
1082 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1083 bool singleplayermode)
1086 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1087 "No menu visible:\n"
1088 "- single tap: button activate\n"
1089 "- double tap: place/use\n"
1090 "- slide finger: look around\n"
1091 "Menu/Inventory visible:\n"
1092 "- double tap (outside):\n"
1094 "- touch stack, touch slot:\n"
1096 "- touch&drag, tap 2nd finger\n"
1097 " --> place single item to slot\n"
1100 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1102 "- Space: jump/climb\n"
1103 "- Shift: sneak/go down\n"
1106 "- Mouse: turn/look\n"
1107 "- Mouse left: dig/punch\n"
1108 "- Mouse right: place/use\n"
1109 "- Mouse wheel: select item\n"
1114 float ypos = singleplayermode ? 0.5 : 0.1;
1115 std::ostringstream os;
1117 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1118 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1119 << wide_to_narrow(wstrgettext("Continue")) << "]";
1121 if (!singleplayermode) {
1122 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1123 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1127 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1128 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1129 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1130 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1132 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1133 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1134 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1135 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1136 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1137 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1138 << g_build_info << "\n"
1139 << "path_user = " << wrap_rows(porting::path_user, 20)
1143 /* Note: FormspecFormSource and LocalFormspecHandler *
1144 * are deleted by guiFormSpecMenu */
1145 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1146 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1148 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1149 (*cur_formspec)->setFocus(L"btn_continue");
1150 (*cur_formspec)->doPause = true;
1153 /******************************************************************************/
1154 static void updateChat(Client &client, f32 dtime, bool show_debug,
1155 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1156 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1158 // Add chat log output for errors to be shown in chat
1159 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1161 // Get new messages from error log buffer
1162 while (!chat_log_error_buf.empty()) {
1163 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1166 // Get new messages from client
1167 std::wstring message;
1169 while (client.getChatMessage(message)) {
1170 chat_backend.addUnparsedMessage(message);
1173 // Remove old messages
1174 chat_backend.step(dtime);
1176 // Display all messages in a static text element
1177 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1178 std::wstring recent_chat = chat_backend.getRecentChat();
1179 unsigned int line_height = g_fontengine->getLineHeight();
1181 guitext_chat->setText(recent_chat.c_str());
1183 // Update gui element size and position
1184 s32 chat_y = 5 + line_height;
1187 chat_y += line_height;
1189 // first pass to calculate height of text to be set
1190 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1191 porting::getWindowSize().X - 20);
1192 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1193 guitext_chat->setRelativePosition(rect);
1195 //now use real height of text and adjust rect according to this size
1196 rect = core::rect<s32>(10, chat_y, width,
1197 chat_y + guitext_chat->getTextHeight());
1200 guitext_chat->setRelativePosition(rect);
1201 // Don't show chat if disabled or empty or profiler is enabled
1202 guitext_chat->setVisible(
1203 show_chat && recent_chat_count != 0 && !show_profiler);
1207 /****************************************************************************
1208 Fast key cache for main game loop
1209 ****************************************************************************/
1211 /* This is faster than using getKeySetting with the tradeoff that functions
1212 * using it must make sure that it's initialised before using it and there is
1213 * no error handling (for example bounds checking). This is really intended for
1214 * use only in the main running loop of the client (the_game()) where the faster
1215 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1216 * (e.g. formspecs) should continue using getKeySetting().
1220 KeyCache() { populate(); }
1234 KEYMAP_ID_INVENTORY,
1241 KEYMAP_ID_CINEMATIC,
1242 KEYMAP_ID_SCREENSHOT,
1243 KEYMAP_ID_TOGGLE_HUD,
1244 KEYMAP_ID_TOGGLE_CHAT,
1245 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1246 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1247 KEYMAP_ID_TOGGLE_DEBUG,
1248 KEYMAP_ID_TOGGLE_PROFILER,
1249 KEYMAP_ID_CAMERA_MODE,
1250 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1251 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1252 KEYMAP_ID_RANGESELECT,
1254 KEYMAP_ID_QUICKTUNE_NEXT,
1255 KEYMAP_ID_QUICKTUNE_PREV,
1256 KEYMAP_ID_QUICKTUNE_INC,
1257 KEYMAP_ID_QUICKTUNE_DEC,
1259 KEYMAP_ID_DEBUG_STACKS,
1261 // Fake keycode for array size and internal checks
1262 KEYMAP_INTERNAL_ENUM_COUNT
1269 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1272 void KeyCache::populate()
1274 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1275 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1276 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1277 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1278 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1279 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1280 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1282 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1283 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1284 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1285 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1286 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1287 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1288 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1289 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1290 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1291 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1292 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1293 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1294 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1295 = getKeySetting("keymap_toggle_force_fog_off");
1296 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1297 = getKeySetting("keymap_toggle_update_camera");
1298 key[KEYMAP_ID_TOGGLE_DEBUG]
1299 = getKeySetting("keymap_toggle_debug");
1300 key[KEYMAP_ID_TOGGLE_PROFILER]
1301 = getKeySetting("keymap_toggle_profiler");
1302 key[KEYMAP_ID_CAMERA_MODE]
1303 = getKeySetting("keymap_camera_mode");
1304 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1305 = getKeySetting("keymap_increase_viewing_range_min");
1306 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1307 = getKeySetting("keymap_decrease_viewing_range_min");
1308 key[KEYMAP_ID_RANGESELECT]
1309 = getKeySetting("keymap_rangeselect");
1311 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1312 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1313 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1314 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1316 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1320 /****************************************************************************
1322 ****************************************************************************/
1324 const float object_hit_delay = 0.2;
1327 u32 last_time, busy_time, sleep_time;
1331 /* The reason the following structs are not anonymous structs within the
1332 * class is that they are not used by the majority of member functions and
1333 * many functions that do require objects of thse types do not modify them
1334 * (so they can be passed as a const qualified parameter)
1336 struct CameraOrientation {
1337 f32 camera_yaw; // "right/left"
1338 f32 camera_pitch; // "up/down"
1341 struct GameRunData {
1344 PointedThing pointed_old;
1348 bool update_wielded_item_trigger;
1349 bool reset_jump_timer;
1350 float nodig_delay_timer;
1352 float dig_time_complete;
1353 float repeat_rightclick_timer;
1354 float object_hit_delay_timer;
1355 float time_from_last_punch;
1356 ClientActiveObject *selected_object;
1360 float update_draw_list_timer;
1361 float statustext_time;
1365 v3f update_draw_list_last_cam_dir;
1367 u32 profiler_current_page;
1368 u32 profiler_max_page; // Number of pages
1371 float time_of_day_smooth;
1375 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1383 Jitter dtime_jitter, busy_time_jitter;
1386 /* Flags that can, or may, change during main game loop
1388 struct VolatileRunFlags {
1394 bool show_profiler_graph;
1395 bool disable_camera_update;
1396 bool first_loop_after_window_activation;
1397 bool camera_offset_changed;
1401 /****************************************************************************
1403 ****************************************************************************/
1405 /* This is not intended to be a public class. If a public class becomes
1406 * desirable then it may be better to create another 'wrapper' class that
1407 * hides most of the stuff in this class (nothing in this class is required
1408 * by any other file) but exposes the public methods/data only.
1416 bool startup(bool *kill,
1418 InputHandler *input,
1419 IrrlichtDevice *device,
1420 const std::string &map_dir,
1421 const std::string &playername,
1422 const std::string &password,
1423 // If address is "", local server is used and address is updated
1424 std::string *address,
1426 std::string &error_message,
1427 ChatBackend *chat_backend,
1428 const SubgameSpec &gamespec, // Used for local game
1429 bool simple_singleplayer_mode);
1436 void extendedResourceCleanup();
1438 // Basic initialisation
1439 bool init(const std::string &map_dir, std::string *address,
1441 const SubgameSpec &gamespec);
1443 bool createSingleplayerServer(const std::string map_dir,
1444 const SubgameSpec &gamespec, u16 port, std::string *address);
1447 bool createClient(const std::string &playername,
1448 const std::string &password, std::string *address, u16 port);
1451 // Client connection
1452 bool connectToServer(const std::string &playername,
1453 const std::string &password, std::string *address, u16 port,
1454 bool *connect_ok, bool *aborted);
1455 bool getServerContent(bool *aborted);
1459 void updateInteractTimers(GameRunData *runData, f32 dtime);
1460 bool checkConnection();
1461 bool handleCallbacks();
1462 void processQueues();
1463 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1464 const FpsControl &draw_times, f32 dtime);
1465 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1467 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1469 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1471 void processKeyboardInput(VolatileRunFlags *flags,
1472 float *statustext_time,
1474 bool *reset_jump_timer,
1475 u32 *profiler_current_page,
1476 u32 profiler_max_page);
1477 void processItemSelection(u16 *new_playeritem);
1479 void dropSelectedItem();
1480 void openInventory();
1482 void toggleFreeMove(float *statustext_time);
1483 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1484 void toggleFast(float *statustext_time);
1485 void toggleNoClip(float *statustext_time);
1486 void toggleCinematic(float *statustext_time);
1488 void toggleChat(float *statustext_time, bool *flag);
1489 void toggleHud(float *statustext_time, bool *flag);
1490 void toggleFog(float *statustext_time, bool *flag);
1491 void toggleDebug(float *statustext_time, bool *show_debug,
1492 bool *show_profiler_graph);
1493 void toggleUpdateCamera(float *statustext_time, bool *flag);
1494 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1495 u32 profiler_max_page);
1497 void increaseViewRange(float *statustext_time);
1498 void decreaseViewRange(float *statustext_time);
1499 void toggleFullViewRange(float *statustext_time);
1501 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1502 void updateCameraOrientation(CameraOrientation *cam,
1503 const VolatileRunFlags &flags);
1504 void updatePlayerControl(const CameraOrientation &cam);
1505 void step(f32 *dtime);
1506 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1507 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1508 float time_from_last_punch);
1509 void updateSound(f32 dtime);
1510 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1511 GameRunData *runData, f32 dtime, bool show_hud,
1513 void handlePointingAtNode(GameRunData *runData,
1514 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1515 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1516 void handlePointingAtObject(GameRunData *runData,
1517 const PointedThing &pointed, const ItemStack &playeritem,
1518 const v3f &player_position, bool show_debug);
1519 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1520 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1522 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1523 RunStats *stats, GameRunData *runData,
1524 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1525 void updateGui(float *statustext_time, const RunStats &stats,
1526 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1527 const CameraOrientation &cam);
1528 void updateProfilerGraphs(ProfilerGraph *graph);
1531 void limitFps(FpsControl *fps_timings, f32 *dtime);
1533 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1534 bool draw_clouds = true);
1537 InputHandler *input;
1542 IWritableTextureSource *texture_src;
1543 IWritableShaderSource *shader_src;
1545 // When created, these will be filled with data received from the server
1546 IWritableItemDefManager *itemdef_manager;
1547 IWritableNodeDefManager *nodedef_manager;
1549 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1550 ISoundManager *sound;
1551 bool sound_is_dummy;
1552 SoundMaker *soundmaker;
1554 ChatBackend *chat_backend;
1556 GUIFormSpecMenu *current_formspec;
1558 EventManager *eventmgr;
1559 QuicktuneShortcutter *quicktune;
1561 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1562 MapDrawControl *draw_control;
1564 Clouds *clouds; // Free using ->Drop()
1565 Sky *sky; // Free using ->Drop()
1566 Inventory *local_inventory;
1570 This class does take ownership/responsibily for cleaning up etc of any of
1571 these items (e.g. device)
1573 IrrlichtDevice *device;
1574 video::IVideoDriver *driver;
1575 scene::ISceneManager *smgr;
1577 std::string *error_message;
1578 IGameDef *gamedef; // Convenience (same as *client)
1579 scene::ISceneNode *skybox;
1582 bool simple_singleplayer_mode;
1585 /* Pre-calculated values
1587 int crack_animation_length;
1591 gui::IGUIStaticText *guitext; // First line of debug text
1592 gui::IGUIStaticText *guitext2; // Second line of debug text
1593 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1594 gui::IGUIStaticText *guitext_status;
1595 gui::IGUIStaticText *guitext_chat; // Chat text
1596 gui::IGUIStaticText *guitext_profiler; // Profiler text
1598 std::wstring infotext;
1599 std::wstring statustext;
1603 IntervalLimiter profiler_interval;
1605 /* TODO: Add a callback function so these can be updated when a setting
1606 * changes. At this point in time it doesn't matter (e.g. /set
1607 * is documented to change server settings only)
1609 * TODO: Local caching of settings is not optimal and should at some stage
1610 * be updated to use a global settings object for getting thse values
1611 * (as opposed to the this local caching). This can be addressed in
1614 bool m_cache_doubletap_jump;
1615 bool m_cache_enable_node_highlighting;
1616 bool m_cache_enable_clouds;
1617 bool m_cache_enable_particles;
1618 bool m_cache_enable_fog;
1619 f32 m_cache_mouse_sensitivity;
1620 f32 m_repeat_right_click_time;
1628 itemdef_manager(NULL),
1629 nodedef_manager(NULL),
1631 sound_is_dummy(false),
1634 current_formspec(NULL),
1637 gui_chat_console(NULL),
1642 local_inventory(NULL),
1645 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1646 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1647 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1648 m_cache_enable_particles = g_settings->getBool("enable_particles");
1649 m_cache_enable_fog = g_settings->getBool("enable_fog");
1650 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1651 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1653 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1658 /****************************************************************************
1660 ****************************************************************************/
1666 if (!sound_is_dummy)
1669 delete server; // deleted first to stop all server threads
1672 delete local_inventory;
1678 delete nodedef_manager;
1679 delete itemdef_manager;
1680 delete draw_control;
1682 extendedResourceCleanup();
1685 bool Game::startup(bool *kill,
1687 InputHandler *input,
1688 IrrlichtDevice *device,
1689 const std::string &map_dir,
1690 const std::string &playername,
1691 const std::string &password,
1692 std::string *address, // can change if simple_singleplayer_mode
1694 std::string &error_message,
1695 ChatBackend *chat_backend,
1696 const SubgameSpec &gamespec,
1697 bool simple_singleplayer_mode)
1700 this->device = device;
1702 this->error_message = &error_message;
1703 this->random_input = random_input;
1704 this->input = input;
1705 this->chat_backend = chat_backend;
1706 this->simple_singleplayer_mode = simple_singleplayer_mode;
1708 driver = device->getVideoDriver();
1709 smgr = device->getSceneManager();
1711 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1713 if (!init(map_dir, address, port, gamespec))
1716 if (!createClient(playername, password, address, port))
1725 ProfilerGraph graph;
1726 RunStats stats = { 0 };
1727 CameraOrientation cam_view_target = { 0 };
1728 CameraOrientation cam_view = { 0 };
1729 GameRunData runData = { 0 };
1730 FpsControl draw_times = { 0 };
1731 VolatileRunFlags flags = { 0 };
1732 f32 dtime; // in seconds
1734 runData.time_from_last_punch = 10.0;
1735 runData.profiler_max_page = 3;
1736 runData.update_wielded_item_trigger = true;
1738 flags.show_chat = true;
1739 flags.show_hud = true;
1740 flags.show_debug = g_settings->getBool("show_debug");
1741 flags.invert_mouse = g_settings->getBool("invert_mouse");
1742 flags.first_loop_after_window_activation = true;
1744 /* Clear the profiler */
1745 Profiler::GraphValues dummyvalues;
1746 g_profiler->graphGet(dummyvalues);
1748 draw_times.last_time = device->getTimer()->getTime();
1750 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1752 &flags.force_fog_off,
1756 std::vector<aabb3f> highlight_boxes;
1758 set_light_table(g_settings->getFloat("display_gamma"));
1760 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1762 /* Must be called immediately after a device->run() call because it
1763 * uses device->getTimer()->getTime()
1765 limitFps(&draw_times, &dtime);
1767 updateStats(&stats, draw_times, dtime);
1768 updateInteractTimers(&runData, dtime);
1770 if (!checkConnection())
1772 if (!handleCallbacks())
1778 hud->resizeHotbar();
1780 updateProfilers(runData, stats, draw_times, dtime);
1781 processUserInput(&flags, &runData, dtime);
1782 // Update camera before player movement to avoid camera lag of one frame
1783 updateCameraDirection(&cam_view_target, &flags);
1784 float cam_smoothing = 0;
1785 if (g_settings->getBool("cinematic"))
1786 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1788 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1789 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1790 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1791 cam_view.camera_yaw) * cam_smoothing;
1792 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1793 cam_view.camera_pitch) * cam_smoothing;
1794 updatePlayerControl(cam_view);
1796 processClientEvents(&cam_view_target, &runData.damage_flash);
1797 updateCamera(&flags, draw_times.busy_time, dtime,
1798 runData.time_from_last_punch);
1800 processPlayerInteraction(highlight_boxes, &runData, dtime,
1801 flags.show_hud, flags.show_debug);
1802 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1804 updateProfilerGraphs(&graph);
1809 void Game::shutdown()
1811 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1816 if (gui_chat_console)
1817 gui_chat_console->drop();
1823 while (g_menumgr.menuCount() > 0) {
1824 g_menumgr.m_stack.front()->setVisible(false);
1825 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1828 if (current_formspec) {
1829 current_formspec->drop();
1830 current_formspec = NULL;
1833 chat_backend->addMessage(L"", L"# Disconnected.");
1834 chat_backend->addMessage(L"", L"");
1838 while (!client->isShutdown()) {
1839 assert(texture_src != NULL);
1840 assert(shader_src != NULL);
1841 texture_src->processQueue();
1842 shader_src->processQueue();
1849 /****************************************************************************/
1850 /****************************************************************************
1852 ****************************************************************************/
1853 /****************************************************************************/
1856 const std::string &map_dir,
1857 std::string *address,
1859 const SubgameSpec &gamespec)
1861 showOverlayMessage(wgettext("Loading..."), 0, 0);
1863 texture_src = createTextureSource(device);
1864 shader_src = createShaderSource(device);
1866 itemdef_manager = createItemDefManager();
1867 nodedef_manager = createNodeDefManager();
1869 eventmgr = new EventManager();
1870 quicktune = new QuicktuneShortcutter();
1872 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1873 && eventmgr && quicktune))
1879 // Create a server if not connecting to an existing one
1880 if (*address == "") {
1881 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1888 bool Game::initSound()
1891 if (g_settings->getBool("enable_sound")) {
1892 infostream << "Attempting to use OpenAL audio" << std::endl;
1893 sound = createOpenALSoundManager(&soundfetcher);
1895 infostream << "Failed to initialize OpenAL audio" << std::endl;
1897 infostream << "Sound disabled." << std::endl;
1901 infostream << "Using dummy audio." << std::endl;
1902 sound = &dummySoundManager;
1903 sound_is_dummy = true;
1906 soundmaker = new SoundMaker(sound, nodedef_manager);
1910 soundmaker->registerReceiver(eventmgr);
1915 bool Game::createSingleplayerServer(const std::string map_dir,
1916 const SubgameSpec &gamespec, u16 port, std::string *address)
1918 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1920 std::string bind_str = g_settings->get("bind_address");
1921 Address bind_addr(0, 0, 0, 0, port);
1923 if (g_settings->getBool("ipv6_server")) {
1924 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1928 bind_addr.Resolve(bind_str.c_str());
1929 } catch (ResolveError &e) {
1930 infostream << "Resolving bind address \"" << bind_str
1931 << "\" failed: " << e.what()
1932 << " -- Listening on all addresses." << std::endl;
1935 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1936 *error_message = "Unable to listen on " +
1937 bind_addr.serializeString() +
1938 " because IPv6 is disabled";
1939 errorstream << *error_message << std::endl;
1943 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1944 bind_addr.isIPv6());
1946 server->start(bind_addr);
1951 bool Game::createClient(const std::string &playername,
1952 const std::string &password, std::string *address, u16 port)
1954 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1956 draw_control = new MapDrawControl;
1960 bool could_connect, connect_aborted;
1962 if (!connectToServer(playername, password, address, port,
1963 &could_connect, &connect_aborted))
1966 if (!could_connect) {
1967 if (error_message->empty() && !connect_aborted) {
1968 // Should not happen if error messages are set properly
1969 *error_message = "Connection failed for unknown reason";
1970 errorstream << *error_message << std::endl;
1975 if (!getServerContent(&connect_aborted)) {
1976 if (error_message->empty() && !connect_aborted) {
1977 // Should not happen if error messages are set properly
1978 *error_message = "Connection failed for unknown reason";
1979 errorstream << *error_message << std::endl;
1984 // Update cached textures, meshes and materials
1985 client->afterContentReceived(device);
1989 camera = new Camera(smgr, *draw_control, gamedef);
1990 if (!camera || !camera->successfullyCreated(*error_message))
1995 if (m_cache_enable_clouds) {
1996 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1998 *error_message = "Memory allocation error (clouds)";
1999 errorstream << *error_message << std::endl;
2006 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2007 skybox = NULL; // This is used/set later on in the main run loop
2009 local_inventory = new Inventory(itemdef_manager);
2011 if (!(sky && local_inventory)) {
2012 *error_message = "Memory allocation error (sky or local inventory)";
2013 errorstream << *error_message << std::endl;
2017 /* Pre-calculated values
2019 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2021 v2u32 size = t->getOriginalSize();
2022 crack_animation_length = size.Y / size.X;
2024 crack_animation_length = 5;
2030 /* Set window caption
2032 std::wstring str = narrow_to_wide(PROJECT_NAME_C);
2034 str += driver->getName();
2036 device->setWindowCaption(str.c_str());
2038 LocalPlayer *player = client->getEnv().getLocalPlayer();
2039 player->hurt_tilt_timer = 0;
2040 player->hurt_tilt_strength = 0;
2042 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2045 *error_message = "Memory error: could not create HUD";
2046 errorstream << *error_message << std::endl;
2053 bool Game::initGui()
2055 // First line of debug text
2056 guitext = guienv->addStaticText(
2057 narrow_to_wide(PROJECT_NAME_C).c_str(),
2058 core::rect<s32>(0, 0, 0, 0),
2059 false, false, guiroot);
2061 // Second line of debug text
2062 guitext2 = guienv->addStaticText(
2064 core::rect<s32>(0, 0, 0, 0),
2065 false, false, guiroot);
2067 // At the middle of the screen
2068 // Object infos are shown in this
2069 guitext_info = guienv->addStaticText(
2071 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2072 false, true, guiroot);
2074 // Status text (displays info when showing and hiding GUI stuff, etc.)
2075 guitext_status = guienv->addStaticText(
2077 core::rect<s32>(0, 0, 0, 0),
2078 false, false, guiroot);
2079 guitext_status->setVisible(false);
2082 guitext_chat = guienv->addStaticText(
2084 core::rect<s32>(0, 0, 0, 0),
2085 //false, false); // Disable word wrap as of now
2086 false, true, guiroot);
2087 // Remove stale "recent" chat messages from previous connections
2088 chat_backend->clearRecentChat();
2090 // Chat backend and console
2091 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2092 -1, chat_backend, client);
2093 if (!gui_chat_console) {
2094 *error_message = "Could not allocate memory for chat console";
2095 errorstream << *error_message << std::endl;
2099 // Profiler text (size is updated when text is updated)
2100 guitext_profiler = guienv->addStaticText(
2102 core::rect<s32>(0, 0, 0, 0),
2103 false, false, guiroot);
2104 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2105 guitext_profiler->setVisible(false);
2106 guitext_profiler->setWordWrap(true);
2108 #ifdef HAVE_TOUCHSCREENGUI
2110 if (g_touchscreengui)
2111 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2118 bool Game::connectToServer(const std::string &playername,
2119 const std::string &password, std::string *address, u16 port,
2120 bool *connect_ok, bool *aborted)
2122 *connect_ok = false; // Let's not be overly optimistic
2124 bool local_server_mode = false;
2126 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2128 Address connect_address(0, 0, 0, 0, port);
2131 connect_address.Resolve(address->c_str());
2133 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2134 //connect_address.Resolve("localhost");
2135 if (connect_address.isIPv6()) {
2136 IPv6AddressBytes addr_bytes;
2137 addr_bytes.bytes[15] = 1;
2138 connect_address.setAddress(&addr_bytes);
2140 connect_address.setAddress(127, 0, 0, 1);
2142 local_server_mode = true;
2144 } catch (ResolveError &e) {
2145 *error_message = std::string("Couldn't resolve address: ") + e.what();
2146 errorstream << *error_message << std::endl;
2150 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2151 *error_message = "Unable to connect to " +
2152 connect_address.serializeString() +
2153 " because IPv6 is disabled";
2154 errorstream << *error_message << std::endl;
2158 client = new Client(device,
2159 playername.c_str(), password,
2160 *draw_control, texture_src, shader_src,
2161 itemdef_manager, nodedef_manager, sound, eventmgr,
2162 connect_address.isIPv6());
2167 gamedef = client; // Client acts as our GameDef
2169 infostream << "Connecting to server at ";
2170 connect_address.print(&infostream);
2171 infostream << std::endl;
2173 client->connect(connect_address, *address,
2174 simple_singleplayer_mode || local_server_mode);
2177 Wait for server to accept connection
2183 FpsControl fps_control = { 0 };
2185 f32 wait_time = 0; // in seconds
2187 fps_control.last_time = device->getTimer()->getTime();
2189 while (device->run()) {
2191 limitFps(&fps_control, &dtime);
2193 // Update client and server
2194 client->step(dtime);
2197 server->step(dtime);
2200 if (client->getState() == LC_Init) {
2206 if (client->accessDenied()) {
2207 *error_message = "Access denied. Reason: "
2208 + client->accessDeniedReason();
2209 errorstream << *error_message << std::endl;
2213 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2215 infostream << "Connect aborted [Escape]" << std::endl;
2220 // Only time out if we aren't waiting for the server we started
2221 if ((*address != "") && (wait_time > 10)) {
2222 *error_message = "Connection timed out.";
2223 errorstream << *error_message << std::endl;
2228 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2230 } catch (con::PeerNotFoundException &e) {
2231 // TODO: Should something be done here? At least an info/error
2239 bool Game::getServerContent(bool *aborted)
2243 FpsControl fps_control = { 0 };
2244 f32 dtime; // in seconds
2246 fps_control.last_time = device->getTimer()->getTime();
2248 while (device->run()) {
2250 limitFps(&fps_control, &dtime);
2252 // Update client and server
2253 client->step(dtime);
2256 server->step(dtime);
2259 if (client->mediaReceived() && client->itemdefReceived() &&
2260 client->nodedefReceived()) {
2265 if (!checkConnection())
2268 if (client->getState() < LC_Init) {
2269 *error_message = "Client disconnected";
2270 errorstream << *error_message << std::endl;
2274 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2276 infostream << "Connect aborted [Escape]" << std::endl;
2283 if (!client->itemdefReceived()) {
2284 const wchar_t *text = wgettext("Item definitions...");
2286 draw_load_screen(text, device, guienv, dtime, progress);
2288 } else if (!client->nodedefReceived()) {
2289 const wchar_t *text = wgettext("Node definitions...");
2291 draw_load_screen(text, device, guienv, dtime, progress);
2294 std::stringstream message;
2295 message.precision(3);
2296 message << gettext("Media...");
2298 if ((USE_CURL == 0) ||
2299 (!g_settings->getBool("enable_remote_media_server"))) {
2300 float cur = client->getCurRate();
2301 std::string cur_unit = gettext("KiB/s");
2305 cur_unit = gettext("MiB/s");
2308 message << " (" << cur << ' ' << cur_unit << ")";
2311 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2312 draw_load_screen(narrow_to_wide(message.str()), device,
2313 guienv, dtime, progress);
2321 /****************************************************************************/
2322 /****************************************************************************
2324 ****************************************************************************/
2325 /****************************************************************************/
2327 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2329 if (runData->nodig_delay_timer >= 0)
2330 runData->nodig_delay_timer -= dtime;
2332 if (runData->object_hit_delay_timer >= 0)
2333 runData->object_hit_delay_timer -= dtime;
2335 runData->time_from_last_punch += dtime;
2339 /* returns false if game should exit, otherwise true
2341 inline bool Game::checkConnection()
2343 if (client->accessDenied()) {
2344 *error_message = "Access denied. Reason: "
2345 + client->accessDeniedReason();
2346 errorstream << *error_message << std::endl;
2354 /* returns false if game should exit, otherwise true
2356 inline bool Game::handleCallbacks()
2358 if (g_gamecallback->disconnect_requested) {
2359 g_gamecallback->disconnect_requested = false;
2363 if (g_gamecallback->changepassword_requested) {
2364 (new GUIPasswordChange(guienv, guiroot, -1,
2365 &g_menumgr, client))->drop();
2366 g_gamecallback->changepassword_requested = false;
2369 if (g_gamecallback->changevolume_requested) {
2370 (new GUIVolumeChange(guienv, guiroot, -1,
2371 &g_menumgr, client))->drop();
2372 g_gamecallback->changevolume_requested = false;
2375 if (g_gamecallback->keyconfig_requested) {
2376 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2377 &g_menumgr))->drop();
2378 g_gamecallback->keyconfig_requested = false;
2381 if (g_gamecallback->keyconfig_changed) {
2382 keycache.populate(); // update the cache with new settings
2383 g_gamecallback->keyconfig_changed = false;
2390 void Game::processQueues()
2392 texture_src->processQueue();
2393 itemdef_manager->processQueue(gamedef);
2394 shader_src->processQueue();
2398 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2399 const FpsControl &draw_times, f32 dtime)
2401 float profiler_print_interval =
2402 g_settings->getFloat("profiler_print_interval");
2403 bool print_to_log = true;
2405 if (profiler_print_interval == 0) {
2406 print_to_log = false;
2407 profiler_print_interval = 5;
2410 if (profiler_interval.step(dtime, profiler_print_interval)) {
2412 infostream << "Profiler:" << std::endl;
2413 g_profiler->print(infostream);
2416 update_profiler_gui(guitext_profiler, g_fontengine,
2417 runData.profiler_current_page, runData.profiler_max_page,
2418 driver->getScreenSize().Height);
2420 g_profiler->clear();
2423 addProfilerGraphs(stats, draw_times, dtime);
2427 void Game::addProfilerGraphs(const RunStats &stats,
2428 const FpsControl &draw_times, f32 dtime)
2430 g_profiler->graphAdd("mainloop_other",
2431 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2433 if (draw_times.sleep_time != 0)
2434 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2435 g_profiler->graphAdd("mainloop_dtime", dtime);
2437 g_profiler->add("Elapsed time", dtime);
2438 g_profiler->avg("FPS", 1. / dtime);
2442 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2449 /* Time average and jitter calculation
2451 jp = &stats->dtime_jitter;
2452 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2454 jitter = dtime - jp->avg;
2456 if (jitter > jp->max)
2459 jp->counter += dtime;
2461 if (jp->counter > 0.0) {
2463 jp->max_sample = jp->max;
2464 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2468 /* Busytime average and jitter calculation
2470 jp = &stats->busy_time_jitter;
2471 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2473 jitter = draw_times.busy_time - jp->avg;
2475 if (jitter > jp->max)
2477 if (jitter < jp->min)
2480 jp->counter += dtime;
2482 if (jp->counter > 0.0) {
2484 jp->max_sample = jp->max;
2485 jp->min_sample = jp->min;
2493 /****************************************************************************
2495 ****************************************************************************/
2497 void Game::processUserInput(VolatileRunFlags *flags,
2498 GameRunData *runData, f32 dtime)
2500 // Reset input if window not active or some menu is active
2501 if (device->isWindowActive() == false
2502 || noMenuActive() == false
2503 || guienv->hasFocus(gui_chat_console)) {
2507 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2508 gui_chat_console->closeConsoleAtOnce();
2511 // Input handler step() (used by the random input generator)
2514 #ifdef HAVE_TOUCHSCREENGUI
2516 if (g_touchscreengui) {
2517 g_touchscreengui->step(dtime);
2523 if (current_formspec != 0)
2524 current_formspec->getAndroidUIInput();
2528 // Increase timer for double tap of "keymap_jump"
2529 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2530 runData->jump_timer += dtime;
2532 processKeyboardInput(
2534 &runData->statustext_time,
2535 &runData->jump_timer,
2536 &runData->reset_jump_timer,
2537 &runData->profiler_current_page,
2538 runData->profiler_max_page);
2540 processItemSelection(&runData->new_playeritem);
2544 void Game::processKeyboardInput(VolatileRunFlags *flags,
2545 float *statustext_time,
2547 bool *reset_jump_timer,
2548 u32 *profiler_current_page,
2549 u32 profiler_max_page)
2552 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2554 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2556 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2558 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2559 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2560 simple_singleplayer_mode);
2561 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2562 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2564 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2565 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2567 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2569 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2570 toggleFreeMove(statustext_time);
2571 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2572 toggleFreeMoveAlt(statustext_time, jump_timer);
2573 *reset_jump_timer = true;
2574 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2575 toggleFast(statustext_time);
2576 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2577 toggleNoClip(statustext_time);
2578 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2579 toggleCinematic(statustext_time);
2580 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2581 client->makeScreenshot(device);
2582 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2583 toggleHud(statustext_time, &flags->show_hud);
2584 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2585 toggleChat(statustext_time, &flags->show_chat);
2586 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2587 toggleFog(statustext_time, &flags->force_fog_off);
2588 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2589 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2590 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2591 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2592 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2593 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2594 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2595 increaseViewRange(statustext_time);
2596 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2597 decreaseViewRange(statustext_time);
2598 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2599 toggleFullViewRange(statustext_time);
2600 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2602 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2604 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2606 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2608 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2609 // Print debug stacks
2610 dstream << "-----------------------------------------"
2612 dstream << DTIME << "Printing debug stacks:" << std::endl;
2613 dstream << "-----------------------------------------"
2615 debug_stacks_print();
2618 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2619 *reset_jump_timer = false;
2625 if (quicktune->hasMessage()) {
2626 std::string msg = quicktune->getMessage();
2627 statustext = narrow_to_wide(msg);
2628 *statustext_time = 0;
2633 void Game::processItemSelection(u16 *new_playeritem)
2635 LocalPlayer *player = client->getEnv().getLocalPlayer();
2637 /* Item selection using mouse wheel
2639 *new_playeritem = client->getPlayerItem();
2641 s32 wheel = input->getMouseWheel();
2642 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2643 player->hud_hotbar_itemcount - 1);
2646 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2648 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2652 /* Item selection using keyboard
2654 for (u16 i = 0; i < 10; i++) {
2655 static const KeyPress *item_keys[10] = {
2656 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2657 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2658 NumberKey + 9, NumberKey + 0,
2661 if (input->wasKeyDown(*item_keys[i])) {
2662 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2663 *new_playeritem = i;
2664 infostream << "Selected item: " << new_playeritem << std::endl;
2672 void Game::dropSelectedItem()
2674 IDropAction *a = new IDropAction();
2676 a->from_inv.setCurrentPlayer();
2677 a->from_list = "main";
2678 a->from_i = client->getPlayerItem();
2679 client->inventoryAction(a);
2683 void Game::openInventory()
2686 * Don't permit to open inventory is CAO or player doesn't exists.
2687 * This prevent showing an empty inventory at player load
2690 LocalPlayer *player = client->getEnv().getLocalPlayer();
2691 if (player == NULL || player->getCAO() == NULL)
2694 infostream << "the_game: " << "Launching inventory" << std::endl;
2696 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2697 TextDest *txt_dst = new TextDestPlayerInventory(client);
2699 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2700 device, fs_src, txt_dst, client);
2702 InventoryLocation inventoryloc;
2703 inventoryloc.setCurrentPlayer();
2704 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2708 void Game::openConsole()
2710 if (!gui_chat_console->isOpenInhibited()) {
2711 // Open up to over half of the screen
2712 gui_chat_console->openConsole(0.6);
2713 guienv->setFocus(gui_chat_console);
2718 void Game::toggleFreeMove(float *statustext_time)
2720 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2722 bool free_move = !g_settings->getBool("free_move");
2723 g_settings->set("free_move", bool_to_cstr(free_move));
2725 *statustext_time = 0;
2726 statustext = msg[free_move];
2727 if (free_move && !client->checkPrivilege("fly"))
2728 statustext += L" (note: no 'fly' privilege)";
2732 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2734 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2735 toggleFreeMove(statustext_time);
2739 void Game::toggleFast(float *statustext_time)
2741 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2742 bool fast_move = !g_settings->getBool("fast_move");
2743 g_settings->set("fast_move", bool_to_cstr(fast_move));
2745 *statustext_time = 0;
2746 statustext = msg[fast_move];
2748 if (fast_move && !client->checkPrivilege("fast"))
2749 statustext += L" (note: no 'fast' privilege)";
2753 void Game::toggleNoClip(float *statustext_time)
2755 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2756 bool noclip = !g_settings->getBool("noclip");
2757 g_settings->set("noclip", bool_to_cstr(noclip));
2759 *statustext_time = 0;
2760 statustext = msg[noclip];
2762 if (noclip && !client->checkPrivilege("noclip"))
2763 statustext += L" (note: no 'noclip' privilege)";
2766 void Game::toggleCinematic(float *statustext_time)
2768 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2769 bool cinematic = !g_settings->getBool("cinematic");
2770 g_settings->set("cinematic", bool_to_cstr(cinematic));
2772 *statustext_time = 0;
2773 statustext = msg[cinematic];
2777 void Game::toggleChat(float *statustext_time, bool *flag)
2779 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2782 *statustext_time = 0;
2783 statustext = msg[*flag];
2787 void Game::toggleHud(float *statustext_time, bool *flag)
2789 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2792 *statustext_time = 0;
2793 statustext = msg[*flag];
2794 if (g_settings->getBool("enable_node_highlighting"))
2795 client->setHighlighted(client->getHighlighted(), *flag);
2799 void Game::toggleFog(float *statustext_time, bool *flag)
2801 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2804 *statustext_time = 0;
2805 statustext = msg[*flag];
2809 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2810 bool *show_profiler_graph)
2812 // Initial / 3x toggle: Chat only
2813 // 1x toggle: Debug text with chat
2814 // 2x toggle: Debug text with profiler graph
2817 *show_profiler_graph = false;
2818 statustext = L"Debug info shown";
2819 } else if (*show_profiler_graph) {
2820 *show_debug = false;
2821 *show_profiler_graph = false;
2822 statustext = L"Debug info and profiler graph hidden";
2824 *show_profiler_graph = true;
2825 statustext = L"Profiler graph shown";
2827 *statustext_time = 0;
2831 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2833 static const wchar_t *msg[] = {
2834 L"Camera update enabled",
2835 L"Camera update disabled"
2839 *statustext_time = 0;
2840 statustext = msg[*flag];
2844 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2845 u32 profiler_max_page)
2847 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2849 // FIXME: This updates the profiler with incomplete values
2850 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2851 profiler_max_page, driver->getScreenSize().Height);
2853 if (*profiler_current_page != 0) {
2854 std::wstringstream sstr;
2855 sstr << "Profiler shown (page " << *profiler_current_page
2856 << " of " << profiler_max_page << ")";
2857 statustext = sstr.str();
2859 statustext = L"Profiler hidden";
2861 *statustext_time = 0;
2865 void Game::increaseViewRange(float *statustext_time)
2867 s16 range = g_settings->getS16("viewing_range_nodes_min");
2868 s16 range_new = range + 10;
2869 g_settings->set("viewing_range_nodes_min", itos(range_new));
2870 statustext = narrow_to_wide("Minimum viewing range changed to "
2872 *statustext_time = 0;
2876 void Game::decreaseViewRange(float *statustext_time)
2878 s16 range = g_settings->getS16("viewing_range_nodes_min");
2879 s16 range_new = range - 10;
2884 g_settings->set("viewing_range_nodes_min", itos(range_new));
2885 statustext = narrow_to_wide("Minimum viewing range changed to "
2887 *statustext_time = 0;
2891 void Game::toggleFullViewRange(float *statustext_time)
2893 static const wchar_t *msg[] = {
2894 L"Disabled full viewing range",
2895 L"Enabled full viewing range"
2898 draw_control->range_all = !draw_control->range_all;
2899 infostream << msg[draw_control->range_all] << std::endl;
2900 statustext = msg[draw_control->range_all];
2901 *statustext_time = 0;
2905 void Game::updateCameraDirection(CameraOrientation *cam,
2906 VolatileRunFlags *flags)
2908 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2911 if (!random_input) {
2912 // Mac OSX gets upset if this is set every frame
2913 if (device->getCursorControl()->isVisible())
2914 device->getCursorControl()->setVisible(false);
2918 if (flags->first_loop_after_window_activation)
2919 flags->first_loop_after_window_activation = false;
2921 updateCameraOrientation(cam, *flags);
2923 input->setMousePos((driver->getScreenSize().Width / 2),
2924 (driver->getScreenSize().Height / 2));
2928 // Mac OSX gets upset if this is set every frame
2929 if (device->getCursorControl()->isVisible() == false)
2930 device->getCursorControl()->setVisible(true);
2933 if (!flags->first_loop_after_window_activation)
2934 flags->first_loop_after_window_activation = true;
2940 void Game::updateCameraOrientation(CameraOrientation *cam,
2941 const VolatileRunFlags &flags)
2943 #ifdef HAVE_TOUCHSCREENGUI
2944 if (g_touchscreengui) {
2945 cam->camera_yaw = g_touchscreengui->getYaw();
2946 cam->camera_pitch = g_touchscreengui->getPitch();
2949 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2950 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2952 if (flags.invert_mouse
2953 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2957 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2958 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2960 #ifdef HAVE_TOUCHSCREENGUI
2964 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2968 void Game::updatePlayerControl(const CameraOrientation &cam)
2970 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2972 PlayerControl control(
2973 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2974 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2975 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2976 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2977 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2978 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2979 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2980 input->getLeftState(),
2981 input->getRightState(),
2987 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2988 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2989 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2990 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2991 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
2992 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2993 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
2994 ( (u32)(input->getLeftState() & 0x1) << 7) |
2995 ( (u32)(input->getRightState() & 0x1) << 8
2999 /* For Android, invert the meaning of holding down the fast button (i.e.
3000 * holding down the fast button -- if there is one -- means walk)
3002 control.aux1 = control.aux1 ^ true;
3003 keypress_bits ^= ((u32)(1U << 5));
3006 client->setPlayerControl(control);
3007 LocalPlayer *player = client->getEnv().getLocalPlayer();
3008 player->keyPressed = keypress_bits;
3014 inline void Game::step(f32 *dtime)
3016 bool can_be_and_is_paused =
3017 (simple_singleplayer_mode && g_menumgr.pausesGame());
3019 if (can_be_and_is_paused) { // This is for a singleplayer server
3020 *dtime = 0; // No time passes
3022 if (server != NULL) {
3023 //TimeTaker timer("server->step(dtime)");
3024 server->step(*dtime);
3027 //TimeTaker timer("client.step(dtime)");
3028 client->step(*dtime);
3033 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3035 ClientEvent event = client->getClientEvent();
3037 LocalPlayer *player = client->getEnv().getLocalPlayer();
3039 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3041 if (event.type == CE_PLAYER_DAMAGE &&
3042 client->getHP() != 0) {
3043 //u16 damage = event.player_damage.amount;
3044 //infostream<<"Player damage: "<<damage<<std::endl;
3046 *damage_flash += 100.0;
3047 *damage_flash += 8.0 * event.player_damage.amount;
3049 player->hurt_tilt_timer = 1.5;
3050 player->hurt_tilt_strength = event.player_damage.amount / 4;
3051 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3053 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3054 gamedef->event()->put(e);
3055 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3056 cam->camera_yaw = event.player_force_move.yaw;
3057 cam->camera_pitch = event.player_force_move.pitch;
3058 } else if (event.type == CE_DEATHSCREEN) {
3059 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3062 chat_backend->addMessage(L"", L"You died.");
3064 /* Handle visualization */
3066 player->hurt_tilt_timer = 0;
3067 player->hurt_tilt_strength = 0;
3069 } else if (event.type == CE_SHOW_FORMSPEC) {
3070 FormspecFormSource *fs_src =
3071 new FormspecFormSource(*(event.show_formspec.formspec));
3072 TextDestPlayerInventory *txt_dst =
3073 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3075 create_formspec_menu(¤t_formspec, client, gamedef,
3076 texture_src, device, fs_src, txt_dst, client);
3078 delete(event.show_formspec.formspec);
3079 delete(event.show_formspec.formname);
3080 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3081 (event.type == CE_ADD_PARTICLESPAWNER) ||
3082 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3083 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3085 } else if (event.type == CE_HUDADD) {
3086 u32 id = event.hudadd.id;
3088 LocalPlayer *player = client->getEnv().getLocalPlayer();
3089 HudElement *e = player->getHud(id);
3092 delete event.hudadd.pos;
3093 delete event.hudadd.name;
3094 delete event.hudadd.scale;
3095 delete event.hudadd.text;
3096 delete event.hudadd.align;
3097 delete event.hudadd.offset;
3098 delete event.hudadd.world_pos;
3099 delete event.hudadd.size;
3104 e->type = (HudElementType)event.hudadd.type;
3105 e->pos = *event.hudadd.pos;
3106 e->name = *event.hudadd.name;
3107 e->scale = *event.hudadd.scale;
3108 e->text = *event.hudadd.text;
3109 e->number = event.hudadd.number;
3110 e->item = event.hudadd.item;
3111 e->dir = event.hudadd.dir;
3112 e->align = *event.hudadd.align;
3113 e->offset = *event.hudadd.offset;
3114 e->world_pos = *event.hudadd.world_pos;
3115 e->size = *event.hudadd.size;
3117 u32 new_id = player->addHud(e);
3118 //if this isn't true our huds aren't consistent
3119 sanity_check(new_id == id);
3121 delete event.hudadd.pos;
3122 delete event.hudadd.name;
3123 delete event.hudadd.scale;
3124 delete event.hudadd.text;
3125 delete event.hudadd.align;
3126 delete event.hudadd.offset;
3127 delete event.hudadd.world_pos;
3128 delete event.hudadd.size;
3129 } else if (event.type == CE_HUDRM) {
3130 HudElement *e = player->removeHud(event.hudrm.id);
3134 } else if (event.type == CE_HUDCHANGE) {
3135 u32 id = event.hudchange.id;
3136 HudElement *e = player->getHud(id);
3139 delete event.hudchange.v3fdata;
3140 delete event.hudchange.v2fdata;
3141 delete event.hudchange.sdata;
3142 delete event.hudchange.v2s32data;
3146 switch (event.hudchange.stat) {
3148 e->pos = *event.hudchange.v2fdata;
3152 e->name = *event.hudchange.sdata;
3155 case HUD_STAT_SCALE:
3156 e->scale = *event.hudchange.v2fdata;
3160 e->text = *event.hudchange.sdata;
3163 case HUD_STAT_NUMBER:
3164 e->number = event.hudchange.data;
3168 e->item = event.hudchange.data;
3172 e->dir = event.hudchange.data;
3175 case HUD_STAT_ALIGN:
3176 e->align = *event.hudchange.v2fdata;
3179 case HUD_STAT_OFFSET:
3180 e->offset = *event.hudchange.v2fdata;
3183 case HUD_STAT_WORLD_POS:
3184 e->world_pos = *event.hudchange.v3fdata;
3188 e->size = *event.hudchange.v2s32data;
3192 delete event.hudchange.v3fdata;
3193 delete event.hudchange.v2fdata;
3194 delete event.hudchange.sdata;
3195 delete event.hudchange.v2s32data;
3196 } else if (event.type == CE_SET_SKY) {
3197 sky->setVisible(false);
3204 // Handle according to type
3205 if (*event.set_sky.type == "regular") {
3206 sky->setVisible(true);
3207 } else if (*event.set_sky.type == "skybox" &&
3208 event.set_sky.params->size() == 6) {
3209 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3210 skybox = smgr->addSkyBoxSceneNode(
3211 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3212 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3213 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3214 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3215 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3216 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3218 // Handle everything else as plain color
3220 if (*event.set_sky.type != "plain")
3221 infostream << "Unknown sky type: "
3222 << (*event.set_sky.type) << std::endl;
3224 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3227 delete event.set_sky.bgcolor;
3228 delete event.set_sky.type;
3229 delete event.set_sky.params;
3230 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3231 bool enable = event.override_day_night_ratio.do_override;
3232 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3233 client->getEnv().setDayNightRatioOverride(enable, value);
3239 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3240 f32 dtime, float time_from_last_punch)
3242 LocalPlayer *player = client->getEnv().getLocalPlayer();
3245 For interaction purposes, get info about the held item
3247 - Is it a usable item?
3248 - Can it point to liquids?
3250 ItemStack playeritem;
3252 InventoryList *mlist = local_inventory->getList("main");
3254 if (mlist && client->getPlayerItem() < mlist->getSize())
3255 playeritem = mlist->getItem(client->getPlayerItem());
3258 ToolCapabilities playeritem_toolcap =
3259 playeritem.getToolCapabilities(itemdef_manager);
3261 v3s16 old_camera_offset = camera->getOffset();
3263 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3264 GenericCAO *playercao = player->getCAO();
3266 // If playercao not loaded, don't change camera
3267 if (playercao == NULL)
3270 camera->toggleCameraMode();
3272 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3275 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3276 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3278 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3279 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3281 camera->step(dtime);
3283 v3f camera_position = camera->getPosition();
3284 v3f camera_direction = camera->getDirection();
3285 f32 camera_fov = camera->getFovMax();
3286 v3s16 camera_offset = camera->getOffset();
3288 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3290 if (!flags->disable_camera_update) {
3291 client->getEnv().getClientMap().updateCamera(camera_position,
3292 camera_direction, camera_fov, camera_offset);
3294 if (flags->camera_offset_changed) {
3295 client->updateCameraOffset(camera_offset);
3296 client->getEnv().updateCameraOffset(camera_offset);
3299 clouds->updateCameraOffset(camera_offset);
3305 void Game::updateSound(f32 dtime)
3307 // Update sound listener
3308 v3s16 camera_offset = camera->getOffset();
3309 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3310 v3f(0, 0, 0), // velocity
3311 camera->getDirection(),
3312 camera->getCameraNode()->getUpVector());
3313 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3316 // Update sound maker
3317 soundmaker->step(dtime);
3319 LocalPlayer *player = client->getEnv().getLocalPlayer();
3321 ClientMap &map = client->getEnv().getClientMap();
3322 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3323 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3327 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3328 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3330 LocalPlayer *player = client->getEnv().getLocalPlayer();
3332 ItemStack playeritem;
3334 InventoryList *mlist = local_inventory->getList("main");
3336 if (mlist && client->getPlayerItem() < mlist->getSize())
3337 playeritem = mlist->getItem(client->getPlayerItem());
3340 const ItemDefinition &playeritem_def =
3341 playeritem.getDefinition(itemdef_manager);
3343 v3f player_position = player->getPosition();
3344 v3f camera_position = camera->getPosition();
3345 v3f camera_direction = camera->getDirection();
3346 v3s16 camera_offset = camera->getOffset();
3350 Calculate what block is the crosshair pointing to
3353 f32 d = playeritem_def.range; // max. distance
3354 f32 d_hand = itemdef_manager->get("").range;
3356 if (d < 0 && d_hand >= 0)
3361 core::line3d<f32> shootline;
3363 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3365 shootline = core::line3d<f32>(camera_position,
3366 camera_position + camera_direction * BS * (d + 1));
3369 // prevent player pointing anything in front-view
3370 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3371 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3374 #ifdef HAVE_TOUCHSCREENGUI
3376 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3377 shootline = g_touchscreengui->getShootline();
3378 shootline.start += intToFloat(camera_offset, BS);
3379 shootline.end += intToFloat(camera_offset, BS);
3384 PointedThing pointed = getPointedThing(
3386 client, player_position, camera_direction,
3387 camera_position, shootline, d,
3388 playeritem_def.liquids_pointable,
3389 !runData->ldown_for_dig,
3393 runData->selected_object);
3395 if (pointed != runData->pointed_old) {
3396 infostream << "Pointing at " << pointed.dump() << std::endl;
3398 if (m_cache_enable_node_highlighting) {
3399 if (pointed.type == POINTEDTHING_NODE) {
3400 client->setHighlighted(pointed.node_undersurface, show_hud);
3402 client->setHighlighted(pointed.node_undersurface, false);
3409 - releasing left mouse button
3410 - pointing away from node
3412 if (runData->digging) {
3413 if (input->getLeftReleased()) {
3414 infostream << "Left button released"
3415 << " (stopped digging)" << std::endl;
3416 runData->digging = false;
3417 } else if (pointed != runData->pointed_old) {
3418 if (pointed.type == POINTEDTHING_NODE
3419 && runData->pointed_old.type == POINTEDTHING_NODE
3420 && pointed.node_undersurface
3421 == runData->pointed_old.node_undersurface) {
3422 // Still pointing to the same node, but a different face.
3425 infostream << "Pointing away from node"
3426 << " (stopped digging)" << std::endl;
3427 runData->digging = false;
3431 if (!runData->digging) {
3432 client->interact(1, runData->pointed_old);
3433 client->setCrack(-1, v3s16(0, 0, 0));
3434 runData->dig_time = 0.0;
3438 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3439 runData->ldown_for_dig = false;
3442 runData->left_punch = false;
3444 soundmaker->m_player_leftpunch_sound.name = "";
3446 if (input->getRightState())
3447 runData->repeat_rightclick_timer += dtime;
3449 runData->repeat_rightclick_timer = 0;
3451 if (playeritem_def.usable && input->getLeftState()) {
3452 if (input->getLeftClicked())
3453 client->interact(4, pointed);
3454 } else if (pointed.type == POINTEDTHING_NODE) {
3455 ToolCapabilities playeritem_toolcap =
3456 playeritem.getToolCapabilities(itemdef_manager);
3457 handlePointingAtNode(runData, pointed, playeritem_def,
3458 playeritem_toolcap, dtime);
3459 } else if (pointed.type == POINTEDTHING_OBJECT) {
3460 handlePointingAtObject(runData, pointed, playeritem,
3461 player_position, show_debug);
3462 } else if (input->getLeftState()) {
3463 // When button is held down in air, show continuous animation
3464 runData->left_punch = true;
3467 runData->pointed_old = pointed;
3469 if (runData->left_punch || input->getLeftClicked())
3470 camera->setDigging(0); // left click animation
3472 input->resetLeftClicked();
3473 input->resetRightClicked();
3475 input->resetLeftReleased();
3476 input->resetRightReleased();
3480 void Game::handlePointingAtNode(GameRunData *runData,
3481 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3482 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3484 v3s16 nodepos = pointed.node_undersurface;
3485 v3s16 neighbourpos = pointed.node_abovesurface;
3488 Check information text of node
3491 ClientMap &map = client->getEnv().getClientMap();
3492 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3495 infotext = narrow_to_wide(meta->getString("infotext"));
3497 MapNode n = map.getNodeNoEx(nodepos);
3499 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3500 infotext = L"Unknown node: ";
3501 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3505 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3506 && client->checkPrivilege("interact")) {
3507 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3510 if ((input->getRightClicked() ||
3511 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3512 client->checkPrivilege("interact")) {
3513 runData->repeat_rightclick_timer = 0;
3514 infostream << "Ground right-clicked" << std::endl;
3516 if (meta && meta->getString("formspec") != "" && !random_input
3517 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3518 infostream << "Launching custom inventory view" << std::endl;
3520 InventoryLocation inventoryloc;
3521 inventoryloc.setNodeMeta(nodepos);
3523 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3524 &client->getEnv().getClientMap(), nodepos);
3525 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3527 create_formspec_menu(¤t_formspec, client, gamedef,
3528 texture_src, device, fs_src, txt_dst, client);
3530 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3532 // Report right click to server
3534 camera->setDigging(1); // right click animation (always shown for feedback)
3536 // If the wielded item has node placement prediction,
3538 bool placed = nodePlacementPrediction(*client,
3540 nodepos, neighbourpos);
3544 client->interact(3, pointed);
3546 soundmaker->m_player_rightpunch_sound =
3547 playeritem_def.sound_place;
3549 soundmaker->m_player_rightpunch_sound =
3553 if (playeritem_def.node_placement_prediction == "" ||
3554 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3555 client->interact(3, pointed); // Report to server
3561 void Game::handlePointingAtObject(GameRunData *runData,
3562 const PointedThing &pointed,
3563 const ItemStack &playeritem,
3564 const v3f &player_position,
3567 infotext = narrow_to_wide(runData->selected_object->infoText());
3569 if (infotext == L"" && show_debug) {
3570 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3573 if (input->getLeftState()) {
3574 bool do_punch = false;
3575 bool do_punch_damage = false;
3577 if (runData->object_hit_delay_timer <= 0.0) {
3579 do_punch_damage = true;
3580 runData->object_hit_delay_timer = object_hit_delay;
3583 if (input->getLeftClicked())
3587 infostream << "Left-clicked object" << std::endl;
3588 runData->left_punch = true;
3591 if (do_punch_damage) {
3592 // Report direct punch
3593 v3f objpos = runData->selected_object->getPosition();
3594 v3f dir = (objpos - player_position).normalize();
3596 bool disable_send = runData->selected_object->directReportPunch(
3597 dir, &playeritem, runData->time_from_last_punch);
3598 runData->time_from_last_punch = 0;
3601 client->interact(0, pointed);
3603 } else if (input->getRightClicked()) {
3604 infostream << "Right-clicked object" << std::endl;
3605 client->interact(3, pointed); // place
3610 void Game::handleDigging(GameRunData *runData,
3611 const PointedThing &pointed, const v3s16 &nodepos,
3612 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3614 if (!runData->digging) {
3615 infostream << "Started digging" << std::endl;
3616 client->interact(0, pointed);
3617 runData->digging = true;
3618 runData->ldown_for_dig = true;
3621 LocalPlayer *player = client->getEnv().getLocalPlayer();
3622 ClientMap &map = client->getEnv().getClientMap();
3623 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3625 // NOTE: Similar piece of code exists on the server side for
3627 // Get digging parameters
3628 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3629 &playeritem_toolcap);
3631 // If can't dig, try hand
3632 if (!params.diggable) {
3633 const ItemDefinition &hand = itemdef_manager->get("");
3634 const ToolCapabilities *tp = hand.tool_capabilities;
3637 params = getDigParams(nodedef_manager->get(n).groups, tp);
3640 if (params.diggable == false) {
3641 // I guess nobody will wait for this long
3642 runData->dig_time_complete = 10000000.0;
3644 runData->dig_time_complete = params.time;
3646 if (m_cache_enable_particles) {
3647 const ContentFeatures &features =
3648 client->getNodeDefManager()->get(n);
3649 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3650 player, nodepos, features.tiles);
3654 if (runData->dig_time_complete >= 0.001) {
3655 runData->dig_index = (float)crack_animation_length
3657 / runData->dig_time_complete;
3659 // This is for torches
3660 runData->dig_index = crack_animation_length;
3663 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3665 if (sound_dig.exists() && params.diggable) {
3666 if (sound_dig.name == "__group") {
3667 if (params.main_group != "") {
3668 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3669 soundmaker->m_player_leftpunch_sound.name =
3670 std::string("default_dig_") +
3674 soundmaker->m_player_leftpunch_sound = sound_dig;
3678 // Don't show cracks if not diggable
3679 if (runData->dig_time_complete >= 100000.0) {
3680 } else if (runData->dig_index < crack_animation_length) {
3681 //TimeTaker timer("client.setTempMod");
3682 //infostream<<"dig_index="<<dig_index<<std::endl;
3683 client->setCrack(runData->dig_index, nodepos);
3685 infostream << "Digging completed" << std::endl;
3686 client->interact(2, pointed);
3687 client->setCrack(-1, v3s16(0, 0, 0));
3688 bool is_valid_position;
3689 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3690 if (is_valid_position)
3691 client->removeNode(nodepos);
3693 if (m_cache_enable_particles) {
3694 const ContentFeatures &features =
3695 client->getNodeDefManager()->get(wasnode);
3696 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3697 player, nodepos, features.tiles);
3700 runData->dig_time = 0;
3701 runData->digging = false;
3703 runData->nodig_delay_timer =
3704 runData->dig_time_complete / (float)crack_animation_length;
3706 // We don't want a corresponding delay to
3707 // very time consuming nodes
3708 if (runData->nodig_delay_timer > 0.3)
3709 runData->nodig_delay_timer = 0.3;
3711 // We want a slight delay to very little
3712 // time consuming nodes
3713 const float mindelay = 0.15;
3715 if (runData->nodig_delay_timer < mindelay)
3716 runData->nodig_delay_timer = mindelay;
3718 // Send event to trigger sound
3719 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3720 gamedef->event()->put(e);
3723 if (runData->dig_time_complete < 100000.0) {
3724 runData->dig_time += dtime;
3726 runData->dig_time = 0;
3727 client->setCrack(-1, nodepos);
3730 camera->setDigging(0); // left click animation
3734 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3735 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3736 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3738 LocalPlayer *player = client->getEnv().getLocalPlayer();
3744 if (draw_control->range_all) {
3745 runData->fog_range = 100000 * BS;
3747 runData->fog_range = draw_control->wanted_range * BS
3748 + 0.0 * MAP_BLOCKSIZE * BS;
3749 runData->fog_range = MYMIN(
3751 (draw_control->farthest_drawn + 20) * BS);
3752 runData->fog_range *= 0.9;
3756 Calculate general brightness
3758 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3759 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3760 float direct_brightness;
3763 if (g_settings->getBool("free_move")) {
3764 direct_brightness = time_brightness;
3765 sunlight_seen = true;
3767 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3768 float old_brightness = sky->getBrightness();
3769 direct_brightness = client->getEnv().getClientMap()
3770 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3771 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3775 float time_of_day = runData->time_of_day;
3776 float time_of_day_smooth = runData->time_of_day_smooth;
3778 time_of_day = client->getEnv().getTimeOfDayF();
3780 const float maxsm = 0.05;
3781 const float todsm = 0.05;
3783 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3784 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3785 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3786 time_of_day_smooth = time_of_day;
3788 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3789 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3790 + (time_of_day + 1.0) * todsm;
3792 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3793 + time_of_day * todsm;
3795 runData->time_of_day = time_of_day;
3796 runData->time_of_day_smooth = time_of_day_smooth;
3798 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3799 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3800 player->getPitch());
3806 v3f player_position = player->getPosition();
3807 if (sky->getCloudsVisible()) {
3808 clouds->setVisible(true);
3809 clouds->step(dtime);
3810 clouds->update(v2f(player_position.X, player_position.Z),
3811 sky->getCloudColor());
3813 clouds->setVisible(false);
3820 client->getParticleManager()->step(dtime);
3826 if (m_cache_enable_fog && !flags.force_fog_off) {
3829 video::EFT_FOG_LINEAR,
3830 runData->fog_range * 0.4,
3831 runData->fog_range * 1.0,
3839 video::EFT_FOG_LINEAR,
3849 Get chat messages from client
3852 v2u32 screensize = driver->getScreenSize();
3854 updateChat(*client, dtime, flags.show_debug, screensize,
3855 flags.show_chat, runData->profiler_current_page,
3856 *chat_backend, guitext_chat);
3862 if (client->getPlayerItem() != runData->new_playeritem)
3863 client->selectPlayerItem(runData->new_playeritem);
3865 // Update local inventory if it has changed
3866 if (client->getLocalInventoryUpdated()) {
3867 //infostream<<"Updating local inventory"<<std::endl;
3868 client->getLocalInventory(*local_inventory);
3869 runData->update_wielded_item_trigger = true;
3872 if (runData->update_wielded_item_trigger) {
3873 // Update wielded tool
3874 InventoryList *mlist = local_inventory->getList("main");
3876 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3877 ItemStack item = mlist->getItem(client->getPlayerItem());
3878 camera->wield(item);
3880 runData->update_wielded_item_trigger = false;
3884 Update block draw list every 200ms or when camera direction has
3887 runData->update_draw_list_timer += dtime;
3889 v3f camera_direction = camera->getDirection();
3890 if (runData->update_draw_list_timer >= 0.2
3891 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3892 || flags.camera_offset_changed) {
3893 runData->update_draw_list_timer = 0;
3894 client->getEnv().getClientMap().updateDrawList(driver);
3895 runData->update_draw_list_last_cam_dir = camera_direction;
3898 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3901 make sure menu is on top
3902 1. Delete formspec menu reference if menu was removed
3903 2. Else, make sure formspec menu is on top
3905 if (current_formspec) {
3906 if (current_formspec->getReferenceCount() == 1) {
3907 current_formspec->drop();
3908 current_formspec = NULL;
3909 } else if (!noMenuActive()) {
3910 guiroot->bringToFront(current_formspec);
3918 video::SColor skycolor = sky->getSkyColor();
3920 TimeTaker tt_draw("mainloop: draw");
3922 TimeTaker timer("beginScene");
3923 driver->beginScene(true, true, skycolor);
3924 stats->beginscenetime = timer.stop(true);
3927 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3928 highlight_boxes, screensize, skycolor, flags.show_hud);
3933 if (flags.show_profiler_graph)
3934 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3939 if (runData->damage_flash > 0.0) {
3940 video::SColor color(std::min(runData->damage_flash, 180.0f),
3944 driver->draw2DRectangle(color,
3945 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3948 runData->damage_flash -= 100.0 * dtime;
3954 if (player->hurt_tilt_timer > 0.0) {
3955 player->hurt_tilt_timer -= dtime * 5;
3957 if (player->hurt_tilt_timer < 0)
3958 player->hurt_tilt_strength = 0;
3965 TimeTaker timer("endScene");
3967 stats->endscenetime = timer.stop(true);
3970 stats->drawtime = tt_draw.stop(true);
3971 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3975 inline static const char *yawToDirectionString(int yaw)
3977 // NOTE: TODO: This can be done mathematically without the else/else-if
3980 const char *player_direction;
3982 yaw = wrapDegrees_0_360(yaw);
3984 if (yaw >= 45 && yaw < 135)
3985 player_direction = "West [-X]";
3986 else if (yaw >= 135 && yaw < 225)
3987 player_direction = "South [-Z]";
3988 else if (yaw >= 225 && yaw < 315)
3989 player_direction = "East [+X]";
3991 player_direction = "North [+Z]";
3993 return player_direction;
3997 void Game::updateGui(float *statustext_time, const RunStats &stats,
3998 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3999 const CameraOrientation &cam)
4001 v2u32 screensize = driver->getScreenSize();
4002 LocalPlayer *player = client->getEnv().getLocalPlayer();
4003 v3f player_position = player->getPosition();
4005 if (flags.show_debug) {
4006 static float drawtime_avg = 0;
4007 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4009 u16 fps = 1.0 / stats.dtime_jitter.avg;
4010 //s32 fps = driver->getFPS();
4012 std::ostringstream os(std::ios_base::binary);
4014 << PROJECT_NAME_C " " << g_version_hash
4016 << " (R: range_all=" << draw_control->range_all << ")"
4017 << std::setprecision(0)
4018 << " drawtime = " << drawtime_avg
4019 << std::setprecision(1)
4020 << ", dtime_jitter = "
4021 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4022 << std::setprecision(1)
4023 << ", v_range = " << draw_control->wanted_range
4024 << std::setprecision(3)
4025 << ", RTT = " << client->getRTT();
4026 guitext->setText(narrow_to_wide(os.str()).c_str());
4027 guitext->setVisible(true);
4028 } else if (flags.show_hud || flags.show_chat) {
4029 std::ostringstream os(std::ios_base::binary);
4030 os << PROJECT_NAME_C " " << g_version_hash;
4031 guitext->setText(narrow_to_wide(os.str()).c_str());
4032 guitext->setVisible(true);
4034 guitext->setVisible(false);
4037 if (guitext->isVisible()) {
4038 core::rect<s32> rect(
4040 screensize.X, 5 + g_fontengine->getTextHeight()
4042 guitext->setRelativePosition(rect);
4045 if (flags.show_debug) {
4046 std::ostringstream os(std::ios_base::binary);
4047 os << std::setprecision(1) << std::fixed
4048 << "(" << (player_position.X / BS)
4049 << ", " << (player_position.Y / BS)
4050 << ", " << (player_position.Z / BS)
4051 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4052 << " " << yawToDirectionString(cam.camera_yaw)
4053 << ") (seed = " << ((u64)client->getMapSeed())
4056 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4057 ClientMap &map = client->getEnv().getClientMap();
4058 const INodeDefManager *nodedef = client->getNodeDefManager();
4059 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4060 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4061 const ContentFeatures &features = nodedef->get(n);
4062 os << " (pointing_at = " << nodedef->get(n).name
4063 << " - " << features.tiledef[0].name.c_str()
4068 guitext2->setText(narrow_to_wide(os.str()).c_str());
4069 guitext2->setVisible(true);
4071 core::rect<s32> rect(
4072 5, 5 + g_fontengine->getTextHeight(),
4073 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4075 guitext2->setRelativePosition(rect);
4077 guitext2->setVisible(false);
4080 guitext_info->setText(infotext.c_str());
4081 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4083 float statustext_time_max = 1.5;
4085 if (!statustext.empty()) {
4086 *statustext_time += dtime;
4088 if (*statustext_time >= statustext_time_max) {
4090 *statustext_time = 0;
4094 guitext_status->setText(statustext.c_str());
4095 guitext_status->setVisible(!statustext.empty());
4097 if (!statustext.empty()) {
4098 s32 status_width = guitext_status->getTextWidth();
4099 s32 status_height = guitext_status->getTextHeight();
4100 s32 status_y = screensize.Y - 150;
4101 s32 status_x = (screensize.X - status_width) / 2;
4102 core::rect<s32> rect(
4103 status_x , status_y - status_height,
4104 status_x + status_width, status_y
4106 guitext_status->setRelativePosition(rect);
4109 video::SColor initial_color(255, 0, 0, 0);
4111 if (guienv->getSkin())
4112 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4114 video::SColor final_color = initial_color;
4115 final_color.setAlpha(0);
4116 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4117 initial_color, final_color,
4118 pow(*statustext_time / statustext_time_max, 2.0f));
4119 guitext_status->setOverrideColor(fade_color);
4120 guitext_status->enableOverrideColor(true);
4125 /* Log times and stuff for visualization */
4126 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4128 Profiler::GraphValues values;
4129 g_profiler->graphGet(values);
4135 /****************************************************************************
4137 ****************************************************************************/
4139 /* On some computers framerate doesn't seem to be automatically limited
4141 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4143 // not using getRealTime is necessary for wine
4144 device->getTimer()->tick(); // Maker sure device time is up-to-date
4145 u32 time = device->getTimer()->getTime();
4146 u32 last_time = fps_timings->last_time;
4148 if (time > last_time) // Make sure time hasn't overflowed
4149 fps_timings->busy_time = time - last_time;
4151 fps_timings->busy_time = 0;
4153 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4154 ? g_settings->getFloat("pause_fps_max")
4155 : g_settings->getFloat("fps_max"));
4157 if (fps_timings->busy_time < frametime_min) {
4158 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4159 device->sleep(fps_timings->sleep_time);
4161 fps_timings->sleep_time = 0;
4164 /* Get the new value of the device timer. Note that device->sleep() may
4165 * not sleep for the entire requested time as sleep may be interrupted and
4166 * therefore it is arguably more accurate to get the new time from the
4167 * device rather than calculating it by adding sleep_time to time.
4170 device->getTimer()->tick(); // Update device timer
4171 time = device->getTimer()->getTime();
4173 if (time > last_time) // Make sure last_time hasn't overflowed
4174 *dtime = (time - last_time) / 1000.0;
4178 fps_timings->last_time = time;
4181 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4182 // pass a copy of it to this function
4183 // Note: \p msg must be allocated using new (not malloc())
4184 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4185 int percent, bool draw_clouds)
4187 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4192 /****************************************************************************/
4193 /****************************************************************************
4195 ****************************************************************************/
4196 /****************************************************************************/
4198 void Game::extendedResourceCleanup()
4200 // Extended resource accounting
4201 infostream << "Irrlicht resources after cleanup:" << std::endl;
4202 infostream << "\tRemaining meshes : "
4203 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4204 infostream << "\tRemaining textures : "
4205 << driver->getTextureCount() << std::endl;
4207 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4208 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4209 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4213 clearTextureNameCache();
4214 infostream << "\tRemaining materials: "
4215 << driver-> getMaterialRendererCount()
4216 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4220 /****************************************************************************/
4221 /****************************************************************************
4222 extern function for launching the game
4223 ****************************************************************************/
4224 /****************************************************************************/
4226 void the_game(bool *kill,
4228 InputHandler *input,
4229 IrrlichtDevice *device,
4231 const std::string &map_dir,
4232 const std::string &playername,
4233 const std::string &password,
4234 const std::string &address, // If empty local server is created
4237 std::string &error_message,
4238 ChatBackend &chat_backend,
4239 const SubgameSpec &gamespec, // Used for local game
4240 bool simple_singleplayer_mode)
4244 /* Make a copy of the server address because if a local singleplayer server
4245 * is created then this is updated and we don't want to change the value
4246 * passed to us by the calling function
4248 std::string server_address = address;
4252 if (game.startup(kill, random_input, input, device, map_dir,
4253 playername, password, &server_address, port,
4254 error_message, &chat_backend, gamespec,
4255 simple_singleplayer_mode)) {
4260 } catch (SerializationError &e) {
4261 error_message = std::string("A serialization error occurred:\n")
4262 + e.what() + "\n\nThe server is probably "
4263 " running a different version of " PROJECT_NAME_C ".";
4264 errorstream << error_message << std::endl;
4265 } catch (ServerError &e) {
4266 error_message = e.what();
4267 errorstream << "ServerError: " << error_message << std::endl;
4268 } catch (ModError &e) {
4269 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4270 errorstream << "ModError: " << error_message << std::endl;